<template>
    <view class="content">
        <view class="uni-form1">
            <uni-forms ref="rulesform" :modelValue="formData" :rules="rules" border label-width="160rpx"
                label-align="right">
                <uni-forms-item :label="$t('企业id')" name="enterprise_code">
                    <uni-easyinput :inputBorder="false" class="uni-mt-5" trim="all" v-model="formData.enterprise_code"
                        :placeholder="$t('请输入企业id')" :clearable="false"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item :label="$t('手机号')" name="username">
                    <uni-easyinput :inputBorder="false" class="uni-mt-5" trim="all" v-model="formData.username"
                        :placeholder="$t('请输入手机号')" :clearable="false"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item :label="$t('密码')" name="password">
                    <uni-easyinput :inputBorder="false" class="uni-mt-5" trim="all" v-model="formData.password"
                        :placeholder="$t('请输入密码')" :clearable="false"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item label="验证码" name="verifyCode">
                    <uni-row class="demo-uni-row">
                        <uni-col :span="16">
                            <uni-easyinput :inputBorder="false" class="uni-mt-5" trim="all"
                                v-model="formData.verifyCode" :placeholder="$t('请输入验证码')"
                                :clearable="false"></uni-easyinput>
                        </uni-col>
                        <uni-col :span="8">
                            <image class="verifyCodeimage" @click="captcha" :src="image" height="35" width="100">
                            </image>
                        </uni-col>
                    </uni-row>
                </uni-forms-item>
                <uni-forms-item label="隐私保护">
                    <checkbox-group class="radio-group" @change="radioprivacy">
                        <label class="privacy">
                            <checkbox value="隐私保护" color="#2159D7" :checked="privacy" />
                            <view class="a-privacy" @click.stop="privacyto">已阅读《隐私保护协议》</view>
                        </label>
                    </checkbox-group>
                </uni-forms-item>
            </uni-forms>
            <view class="foo-button">

                <view>
                    <uv-button :custom-style="submitButton" :text="$t('密码登录')" :disabled="disabled"
                        @click="submit"></uv-button>
                </view>
            </view>
        </view>

        <view class="footer-img">
            <view class="wechat-login-container">
                <uv-icon name="weixin-circle-fill" color="#2aae67" size="60" @click="getTenantList"></uv-icon>
                <text class="wechat-login-text">微信登录</text>
            </view>
        </view>
    </view>

    <uv-popup ref="popup" mode="bottom">
        <view class="popup">
            <uv-cell-group>
                <uv-cell v-for="v in  tenant" :key="v.id" :title="v.name" :value="v.enterprise_code"
                    @click="weixinlogin(v.enterprise_code)">
                </uv-cell>
            </uv-cell-group>
        </view>
    </uv-popup>
</template>

<script setup lang="ts">
import api, { apiget, forceHideLoading } from '@/api';
import { navigateTo } from '@/util/navigator';
import { submitButton } from '@/util/style';
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import dayjs from 'dayjs';
import { ref, onMounted, computed, inject } from 'vue'
import { useI18n } from 'vue-i18n';

const $t = useI18n().t
const formData = ref({
    username: '',
    enterprise_code: '',
    password: '',
    captchaId: '',
    verifyCode: ''
})
const rulesform = ref()
const popup = ref()

const refresh = inject<Function>('refresh')


const rules = {
    username: {
        rules: [
            {
                required: true,
                errorMessage: $t('请输入手机号'),
            },
        ],
    },
    enterprise_code: {
        rules: [
            {
                required: true,
                errorMessage: $t('请输入企业码'),
            },
        ],
    },
    password: {
        rules: [
            {
                required: true,
                errorMessage: $t('请输入密码'),
            },
        ],
    },
    verifyCode: {
        rules: [
            {
                required: true,
                errorMessage: $t('请输入验证码'),
            },
        ],
    },


}

const privacy = ref(false)

const image = ref('')

function privacyto() {
    navigateTo('/pages/user/privacy')
}

uni.showShareMenu({
    withShareTicket: true,
    success(e) {
        console.log("success");
        console.log(e);
    },
    fail(f) {
        console.log("fail");
        console.log(f);
    },
});

const t = ref(false)

onLoad((option) => {
    t.value = !!option?.t
})

onShow(() => {
    const checked = uni.getStorageSync('checked');
    if (checked) {
        privacy.value = checked
    }
})


function radioprivacy(e: any) {
    privacy.value = !privacy.value
}


const disabled = computed(() => {
    if (privacy.value) {
        return !![formData.value?.username, formData.value?.enterprise_code, formData.value?.password, formData.value?.verifyCode, formData.value?.captchaId].filter(e => !e).length
    }
    return true
})

const array = Array.from({ length: 9 }).map((e, k) => {
    return dayjs().get('year') - k + 5
})






function submit(e: any) {
    rulesform.value?.validate().then((res: any) => {
        // 设置请求超时处理
        const timeoutId = setTimeout(() => {
            uni.hideLoading()
            uni.showToast({
                icon: 'error',
                title: '请求超时，请检查网络连接',
                duration: 3000
            })
            captcha()
        }, 15000) // 15秒超时

        api('/wechat/index/login', formData.value).then(() => {
            clearTimeout(timeoutId)
            uni.showToast({
                title: '登录成功',
                duration: 2500
            })
            start()
            if (refresh) {
                refresh()
            }
        }).catch(f => {
            clearTimeout(timeoutId)
            captcha()
            console.log(f)
            // 确保错误信息正确显示
            const errorMessage = f || '登录失败，请检查账号密码或企业ID是否正确'
            uni.showToast({
                icon: 'error',
                title: errorMessage,
                duration: 3000
            })
        })
    }).catch((err: any) => {
        console.log('表单验证失败:', err)
    })

}


function weixinlogin(enterprise_code?: string) {
    if (enterprise_code) {
        // 设置请求超时处理
        const timeoutId = setTimeout(() => {
            uni.hideLoading()
            uni.showToast({
                icon: 'error',
                title: '请求超时，请检查网络连接',
                duration: 3000
            })
        }, 15000) // 15秒超时

        api('/wechat/index/weixinlogin', { enterprise_code })
            .then(c => {
                clearTimeout(timeoutId)
                popup.value?.close()
                start()
                if (refresh) {
                    refresh()
                }
            }).catch(f => {
                clearTimeout(timeoutId)
                console.log(f)
                const errorMessage = f || '微信登录失败，请稍后重试'
                uni.showToast({
                    icon: 'error',
                    title: errorMessage,
                    duration: 3000
                })
            })
    }

}

const tenant = ref<Eps.TenantListEntity[]>([])
function getTenantList() {
    // 设置请求超时处理
    const timeoutId = setTimeout(() => {
        uni.hideLoading()
        uni.showToast({
            icon: 'error',
            title: '请求超时，请检查网络连接',
            duration: 3000
        })
    }, 15000) // 15秒超时

    api<Eps.UserInfoEntity>('/wechat/index/getTenantList').then(e => {
        clearTimeout(timeoutId)
        if (e?.tenant_user.length === 1) {
            weixinlogin(e.tenant_user[0].tenant.enterprise_code)
        } else if (e?.tenant_user.length === 0) {
            uni.showToast({
                icon: 'error',
                title: $t('您没有绑定任何企业请绑定'),
                duration: 3000
            })
        } else {
            tenant.value = e.tenant_user.map((e: any) => e.tenant)
            popup.value?.open()
        }
    }).catch(c => {
        clearTimeout(timeoutId)
        const errorMessage = c || '获取企业列表失败'
        uni.showToast({
            icon: 'error',
            title: errorMessage,
            duration: 3000
        })
    })
}

function captcha() {
    start()
}

function start() {
    apiget<{ data: string, captchaId: string }>('/admin/base/open/captcha', {
        type: 'png', height: 45, width: 150, color: '#000'
    }).then((e) => {
        if (e) {
            image.value = e.data
            formData.value.captchaId = e.captchaId

        } else {
            console.log(e)
        }
    }).catch(f => {
        console.log(f)
    })
}

onMounted(() => {
    start()
})

// 添加组件卸载时的清理工作
onUnload(() => {
    // 强制隐藏loading，防止页面切换后仍然显示loading
    forceHideLoading()
})

</script>

<style scoped lang="scss">
.content {
    width: 100vw;
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: 100vh;
}

.uni-form-item .label {
    padding: 20rpx 0;
}

.uni-form1 {
    width: 100vw;
    margin-bottom: 24rpx;
    flex: 1 0 auto;
}

.avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    border: 1px solid var(--color-primary);
}

.footer-img {
    height: 220rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}

.wechat-login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.wechat-login-text {
    margin-top: 16rpx;
    font-size: 28rpx;
    color: #2aae67;
    font-weight: 500;
}

.uni-mt-5 {
    width: 75vh;
}

.radio-group {
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: center;
    gap: 40rpx;
    padding-left: 10px;

}

.header {
    font-family: PingFangSC;
    color: #333333;
    font-weight: 600;
    font-size: 36rpx;
    margin-top: 1.5vh;

}

.header-info {
    font-family: PingFangSC;
    color: #333333;
    font-weight: 400;
    font-size: 26rpx;
    margin-top: 1vh;
    margin-bottom: 3.5vh;
}

.border-1 {
    border: 1px solid #aaaaaa;
}

.privacy {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding-right: 20rpx;
    padding-left: 20rpx;
    flex: 1;
}

.a-privacy {
    color: #409eff;
}

.verifyCodeimage {
    width: 160rpx;
    height: 70rpx;
}

.foo-button {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    width: 100%;

    view {
        flex: 1 0 0%;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
    }
}

.popup {
    width: 100vw;
    height: 65vh;
}
</style>